package mango.orm.mysql;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Types;

import mango.functions.FuncString;
import mango.orm.Extracter;
import mango.orm.entity.Entity;

public class MySqlExtracter implements Extracter {

    public Entity extract(Class<? extends Entity> clazz, ResultSet rs) throws Exception {
        ResultSetMetaData rm = rs.getMetaData();
        Entity ret = clazz.newInstance();
        for (int i = 1; i <= rm.getColumnCount(); i++) {
            String label = rm.getColumnLabel(i);
//            if ("rownum_".equalsIgnoreCase(label)) {
//                ret.setRowNum(rs.getInt("rownum_"));
//                continue;
//            }
            switch (rm.getColumnType(i)) {
            case Types.VARCHAR:
            case Types.CHAR:
            case Types.LONGVARCHAR:
            	ret.set(label.toUpperCase(), FuncString.encodeIfString(rs.getString(i)));
            	break;
            case Types.DATE:
            case Types.TIMESTAMP:
                java.sql.Date d = rs.getDate(i);
                if (d != null) {
                    ret.set(label.toUpperCase(), new java.util.Date(d.getTime()));
                }
                else {
                    ret.set(label.toUpperCase(), null);
                }
                break;
            case Types.TIME:
                java.sql.Time dt = rs.getTime(i);
                if (dt != null) {
                    ret.set(label.toUpperCase(), new java.util.Date(dt.getTime()));
                }
                else {
                    ret.set(label.toUpperCase(), null);
                }
                break;
            case Types.CLOB:
                ret.set(label.toUpperCase(), FuncString.encodeIfString(rs.getString(i)));
                break;
            case Types.BLOB:
                ret.set(label.toUpperCase(), rs.getBinaryStream(i));
                break;
            default:
                ret.set(label.toUpperCase(), FuncString.encodeIfString(rs.getObject(i)));
                break;
            }
        }
        return ret;
    }

}
